﻿using SuperX.Common;
using SuperX.Common.Log;
using SuperX.Common.Respository;
using SuperX.DataCenterService.Listener;
using SuperX.DataCenterService.MomAPI.Model;
using SuperX.DataCenterService.RabbitMQ;
using SuperX.DataCenterService.WebAPI;
using SuperX.MiddlewareBase;
using System;

namespace SuperX.DataCenterService
{
    public class DataCenterServer : HostService
    {
        public RabbitMQManager RabbitMQManager { get; set; }
        private WebApiHost ApiHost = null;
        public override string ServiceType { get; set; }
        public DataCenterConfig Config { get; set; }
        public RemoteServer RemoteServer;

        public static int RunIndex { get; set; } = 100;

        public override bool Exit()
        {
            return true;
        }

        public override bool Init()
        {
            ApiHost = new WebApiHost(Config);
            DataCenterController controller = new DataCenterController(this);
            ScreenDesginController screenDesgin = new ScreenDesginController(this);
            RabbitMQManager = new RabbitMQManager(Config);

            return true;
        }

        public override bool Load(string fileName)
        {
            FileName = fileName;
            Repository = new JsonRepository(FileName);
            Repository.Load(typeof(DataCenterConfig));
            Config = Repository.Model as DataCenterConfig;
            if (Config == null)
            {
                CreateCfgFile();
            }
            return true;
        }

        public override bool SaveAs(string fileName)
        {
            Repository = new JsonRepository(fileName) { Model = Config };
            Repository.Save();
            return true;
        }

        public override bool Start()
        {
            try
            {
                Logger.Info("正在初始化RabbitMQ客户端 ... ");
                RabbitMQManager.Init();
                Logger.Info("RabbitMQ客户端初始化完成 ... ");
                Logger.Info($"{nameof(DataCenterServer)}初始化成功");
                ApiHost.Start();
                RabbitMQManager.Start();
                RemoteServer = RemoteServer.Instance;
                RemoteServer.Init();
                Logger.Info($"{this.GetType().Name}启动");
            }
            catch (Exception ex)
            {
                Logger.Error("Error:" + ex.Message);
            }
            return true;
        }

        public override bool Stop()
        {
            Logger.Info($"{GetType().Name}停止...");
            try
            {
                ApiHost.Stop();
                RabbitMQManager.Stop();
                RemoteServer.Dispose();
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
            }
            return true;
        }

        private void CreateCfgFile()
        {
            DataCenterConfig config = new DataCenterConfig();
            Config = config;
            SaveAs(FullFileName);
        }
    }
}